"""
定义sku增删改查相关视图
"""

from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from meiduo_admin.serializers.sku_serializers import *
from meiduo_admin.custom_page import MyPage


# 新建sku指定从属spu的可选的规格信息
class SPUSpecOptionView(ListAPIView):
    queryset = SPUSpecification.objects.all()
    serializer_class = SPUSpecOptModelSerializer

    # 需要根据路径中传递的spu的主键，过滤出指定的可选规格
    def get_queryset(self):
        # 1、获取路径中的spu的主键
        # 在非视图函数中，如何获取路径分组参数呢；
        # 框架会把命名分组路径参数封装在self.kwargs字典中，key就是分组的名字，value就是正则提取的前端传值
        spu_id =  self.kwargs.get('pk')
        # 2、根据spu主键过滤出可选规格，序列化
        # 根据spu_id过滤出与当前spu关联的多个规格信息
        return self.queryset.filter(
            spu_id=spu_id
        )




# 新建sku可选spu视图
class SPUSimpleView(ListAPIView):
    queryset = SPU.objects.all()
    serializer_class = SPUSimpleModelSerializer


# 新建sku可选分类视图
class GoodsCategoryView(ListAPIView):
    queryset = GoodsCategory.objects.all()
    serializer_class = GoodsCategoryModelSerializer

    def get_queryset(self):
        """过滤出三级分类"""
        return self.queryset.filter(
            parent_id__gt=37 # parent_id大于37的是三级分类
        )



class SKUModeViewSet(ModelViewSet):
    queryset = SKU.objects.all()
    serializer_class = SKUDetailModelSerializer
    pagination_class = MyPage

    def get_queryset(self):
        """重写的目的是实现根据keyword过滤"""
        keyword = self.request.query_params.get("keyword")
        if not keyword:
            return self.queryset.all()
        return self.queryset.filter(name__contains=keyword)